package com.shuogg;


import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
import com.shuogg.proto.GpsData;

/**
 * Created by shuoGG on 2018/6/20
 *
 * <a href="https://blog.csdn.net/u011518120/article/details/54604615">ProtoBuf3</a>
 *
 * JavaBean为GpsData.gps_data, gps_data是核心
 */
public class TestGpsProtoBuf {
    public static void main(String[] args) throws InvalidProtocolBufferException {
        /* 构建GPS模型 */
        GpsData.gps_data.Builder gps_builder = GpsData.gps_data.newBuilder();
        gps_builder.setAltitude(1);
        gps_builder.setDataTime("2017-12-17 16:21:44");
        gps_builder.setGpsStatus(1);
        gps_builder.setLat(39.123);
        gps_builder.setLon(120.112);
        gps_builder.setDirection(30.2F);
        gps_builder.setId(100L);
        GpsData.gps_data gps_data = gps_builder.build();
        System.out.println(gps_data);

        /* 序列化之后生成的byte[] */
        byte[] gpsObjBytes = gps_data.toByteArray();
        System.out.println("Bytes length is " + gpsObjBytes.length);

        /*  反序列化 */
        GpsData.gps_data gpsObj;
        gpsObj = GpsData.gps_data.parseFrom(gps_data.toByteArray());
        System.out.print(gpsObj);

        /* dataObj转Json */
        String jsonGps = JsonFormat.printer().print(gpsObj);
        System.out.println(jsonGps);
    }
}
